<template>
  <div class="step-container">
    <a-card class="checkout-card">
      <!-- 收货地址 -->
      <div class="section">
        <div class="section-header">
          <h3>Shipping Address</h3>
          <a-button type="link" @click="showAddressSelection" v-if="!showAddressList">Change Delivery Address</a-button>
        </div>

        <!-- 默认显示已选中的地址 -->
        <div v-if="!showAddressList && selectedAddress" class="selected-address">
          <div class="selected-address-info">
            <div class="address-header">
              <span class="name">{{ selectedAddress.name }}</span>
              <span class="phone">{{ selectedAddress.phone }}</span>
              <a-tag v-if="selectedAddress.is_default" color="blue">Default</a-tag>
            </div>
            <div class="address-detail">
              {{ selectedAddress.province }} {{ selectedAddress.city }} {{ selectedAddress.district }}
              {{ selectedAddress.detail }}
            </div>
          </div>
          <div class="address-action">
            <a-button type="link" @click="showAddressSelection">Change</a-button>
          </div>
        </div>

        <!-- 无地址提示 -->
        <div v-else-if="!showAddressList && !selectedAddress" class="no-address">
          <a-empty description="You don't have a delivery address yet"/>
          <a-button type="primary" @click="showAddAddressModal" class="add-address-btn">Add New Address</a-button>
        </div>

        <!-- 地址选择列表 -->
        <div v-if="showAddressList">
          <div class="address-list-header">
            <span>Please select the delivery address</span>
            <a-button @click="showAddAddressModal">Add New Address</a-button>
          </div>
          <a-radio-group v-model:value="selectedAddressId">
            <a-radio
                v-for="address in addresses"
                :key="address.id"
                :value="address.id"
                class="address-radio"
            >
              <div class="address-info">
                <div class="address-header">
                  <span class="name">{{ address.name }}</span>
                  <span class="phone">{{ address.phone }}</span>
                  <a-tag v-if="address.is_default" color="blue">Default</a-tag>
                </div>
                <div class="address-detail">
                  {{ address.province }} {{ address.city }} {{ address.district }} {{ address.detail }}
                </div>
              </div>
            </a-radio>
          </a-radio-group>
          <div class="address-list-footer">
            <a-button @click="hideAddressSelection">Confirm</a-button>
          </div>
        </div>
      </div>

      <a-divider/>

      <!-- 运费选择 -->
      <div class="section">
        <div class="section-header">
          <h3>Shipping Options</h3>
          <a-button @click="expandShippingOptions = !expandShippingOptions">
            {{ expandShippingOptions ? 'Close' : 'Change Shipping Options' }}
          </a-button>
        </div>

        <!-- 已选择的配送方式显示（折叠状态） -->
        <div v-if="!expandShippingOptions" class="selected-shipping">
          <div class="selected-shipping-info">
            <div class="shipping-name">
              <span class="shipping-title">{{ selectedShippingData?.title || 'Please Select Shipping Method' }}</span>
              <span v-if="selectedShippingMethod === 2 && goodsTotal >= 99" class="shipping-tag">FREE SHIPPING</span>
              <span v-else-if="selectedShippingData" class="shipping-price">{{
                  useCurrency.currentCurrency.unit
                }}{{ proxy.$ConvertPrice(selectedShippingData.price) }}</span>
            </div>
            <div class="shipping-desc" v-if="selectedShippingData">
              {{ selectedShippingData.description }}
            </div>

            <!-- 已选择的保险选项 -->
            <div class="selected-add-ons" v-if="shippingInsurance || dutyInsurance">
              <div class="add-on-tag" v-if="shippingInsurance">{{ insuranceOptions[0]?.title || 'Shipping Insurance' }}
                ({{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(shippingInsuranceFee) }})
              </div>
              <div class="add-on-tag" v-if="dutyInsurance">{{ insuranceOptions[1]?.title || 'Duty Insurance' }}
                ({{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(dutyInsuranceFee) }})
              </div>
            </div>
          </div>
          <div class="shipping-action">
            <a-button type="link" @click="expandShippingOptions = true">Change</a-button>
          </div>
        </div>

        <!-- 展开状态的配送方式选择 -->
        <div v-if="expandShippingOptions">
          <a-radio-group v-model:value="selectedShippingMethod" class="shipping-options"
                         @change="handleShippingMethodChange">
            <a-radio :value="item.id" class="shipping-option" v-for="(item,index) in shippingMethod" :key="index">
              <div class="shipping-option-content">
                <div class="shipping-name" v-if="item.id === 2 && goodsTotal >= 99">
                  <span class="shipping-title">{{ item.title }}</span>
                  <span class="original-price">{{ useCurrency.currentCurrency.unit }}{{
                      proxy.$ConvertPrice(item.price)
                    }}</span>
                  <span class="shipping-tag">FREE SHIPPING</span>
                </div>
                <div class="shipping-name" v-else>
                  <span class="shipping-title">{{ item.title }}</span>
                  <span class="shipping-price">{{ useCurrency.currentCurrency.unit }}{{
                      proxy.$ConvertPrice(item.price)
                    }}</span>
                </div>
                <div class="shipping-desc">{{ item.description }}</div>
              </div>
            </a-radio>

            <!--            <a-radio :value="'express'" class="shipping-option">-->
            <!--              <div class="shipping-option-content">-->
            <!--                <div class="shipping-name">-->
            <!--                  <span class="shipping-title">快速配送</span>-->
            <!--                  <span class="shipping-price">¥{{ expressShippingFee.toFixed(2) }}</span>-->
            <!--                </div>-->
            <!--                <div class="shipping-desc">预计配送时间 2-3 天</div>-->
            <!--              </div>-->
            <!--            </a-radio>-->
          </a-radio-group>

          <div class="shipping-add-ons" v-for="(item,index) in insuranceOptions" :key="index">
            <a-checkbox :id="item.id" v-model:checked="item.checked" class="shipping-add-on"
                        @change="handleInsuranceChange">
              <div class="add-on-content">
                <div class="add-on-name">
                  <span>{{ item.title }}</span>
                  <span class="add-on-price">{{ useCurrency.currentCurrency.unit }}{{
                      proxy.$ConvertPrice(item.price)
                    }}</span>
                </div>
                <div class="add-on-desc">{{ item.description }}</div>
              </div>
            </a-checkbox>

            <!--            <a-checkbox v-model:checked="dutyInsurance" class="shipping-add-on">-->
            <!--              <div class="add-on-content">-->
            <!--                <div class="add-on-name">-->
            <!--                  <span>关税保险</span>-->
            <!--                  <span class="add-on-price">¥{{ dutyInsuranceFee.toFixed(2) }}</span>-->
            <!--                </div>-->
            <!--                <div class="add-on-desc">预付关税和手续费</div>-->
            <!--              </div>-->
            <!--            </a-checkbox>-->
          </div>

          <div class="shipping-options-footer">
            <a-button @click="expandShippingOptions = false">Confirm</a-button>
          </div>
        </div>
      </div>

      <a-divider/>

      <!-- 优惠券使用 -->
      <div class="section">
        <div class="section-header">
          <h3>Coupons</h3>
          <a-button @click="expandCouponList = !expandCouponList">
            {{ expandCouponList ? 'Close' : 'Select Coupons' }}
          </a-button>
        </div>

        <!-- 已选优惠券显示 -->
        <div v-if="selectedCouponId && !expandCouponList" class="selected-coupon">
          <div class="selected-coupon-info">
            <div class="coupon-name">
              Selected coupons:
              <span class="coupon-value">{{ selectedCouponName }}</span>
              <span class="coupon-discount">-{{
                  useCurrency.currentCurrency.unit
                }}{{ proxy.$ConvertPrice(couponDiscount) }}</span>
            </div>
          </div>
          <div class="coupon-action">
            <a-button type="link" @click="expandCouponList = true">Change</a-button>
          </div>
        </div>

        <!-- 未选择优惠券且未展开列表时的提示 -->
        <div v-if="!selectedCouponId && !expandCouponList" class="no-coupon-selected">
          <span>{{ availableCoupons.length > 0 ? 'You have coupons available' : 'No coupons available' }}</span>
          <!--          <a-button v-if="availableCoupons.length > 0" type="link" @click="expandCouponList = true">选择优惠券</a-button>-->
        </div>

        <!-- 可用优惠券列表 -->
        <div v-if="expandCouponList" class="available-coupons">
          <div class="available-coupons-header">
            <span>Coupons available ({{ availableCoupons.length }})</span>
          </div>
          <a-radio-group v-model:value="selectedCouponId" class="coupon-list" @change="handleCouponChange">
            <a-radio :value="null" class="coupon-option">
              <div class="coupon-none">No coupons used</div>
            </a-radio>

            <a-radio
                v-for="coupon in availableCoupons"
                :key="coupon.id"
                :value="coupon.id"
                class="coupon-option"
            >
              <div class="coupon-card" :class="{ 'selected': selectedCouponId === coupon.id }">
                <div class="coupon-amount">{{
                    useCurrency.currentCurrency.unit
                  }}{{ proxy.$ConvertPrice(coupon.discount_amount) }}
                </div>
                <div class="coupon-info">
                  <div class="coupon-name">{{ coupon.name }}</div>
                  <div class="coupon-desc">{{ coupon.description }}</div>
                  <div class="coupon-valid">Validity period:
                    <DateFormatter :value="coupon.end_time" format="MM/DD/YYYY HH:mm:ss" fallback="No"/>
                  </div>
                </div>
              </div>
            </a-radio>
          </a-radio-group>
          <div class="coupon-list-footer">
            <a-button @click="expandCouponList = false">Confirm</a-button>
          </div>
        </div>
      </div>

      <a-divider/>

      <!-- 支付方式 -->
      <div class="section">
        <h3>Payment method</h3>
        <a-radio-group v-model:value="paymentMethod">
          <a-radio value="creditcard" class="payment-radio">
            <!--            <template #radio="{ checked }">-->
            <div class="payment-option">
              <CreditCardOutlined class="payment-icon"/>
              <span>credit</span>
            </div>
            <!--            </template>-->
          </a-radio>
        </a-radio-group>
      </div>

      <a-divider/>

      <!-- 最终金额确认 -->
      <div class="section final-amount-section">
        <h3>Order Summary</h3>
        <div class="final-amount-container">
          <div class="final-amount-details">
            <div class="final-amount-row">
              <span>Total product amount</span>
              <span>{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(goodsTotal) }}</span>
            </div>
            <div class="final-amount-row">
              <span>Freight</span>
              <span>{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(totalShippingFee) }}</span>
            </div>
            <div class="final-amount-row">
              <span>Shipping Insurance</span>
              <span>{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(totalShippingInsuranceFee) }}</span>
            </div>
            <div class="final-amount-row">
              <span>Duty Insurance</span>
              <span>{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(totalDutyInsuranceFee) }}</span>
            </div>
            <div class="final-amount-row discount" v-if="couponDiscount > 0">
              <span>Save</span>
              <span>-{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(couponDiscount) }}</span>
            </div>
          </div>
          <div class="final-amount-total">
            <span>Order Total</span>
            <span class="amount-value">{{ useCurrency.currentCurrency.unit }}{{
                proxy.$ConvertPrice(finalAmount)
              }}</span>
          </div>
        </div>
      </div>
    </a-card>

    <div class="step-footer">
      <a-button @click="prevStep">Previous</a-button>
      <a-button type="primary" @click="nextStep" :disabled="!selectedAddressId">Next</a-button>
    </div>

    <!-- 添加地址模态框 -->
    <a-modal
        v-model:open="addressModalVisible"
        title="Add Address"
        @ok="saveAddress"
        :confirmLoading="addressLoading"
        width="600px"
    >
      <AddressForm
          ref="addressFormRef"
          :initialData="formData"
          :defaultAddress="isDefaultAddress"
          @update:data="onFormDataUpdate"
          @update:isDefault="onDefaultUpdate"
          @update:phoneValid="onPhoneValidUpdate"
      />
    </a-modal>
  </div>
</template>

<script setup>
import {ref, onMounted, computed, watch, getCurrentInstance} from 'vue';
import {useRouter, useRoute} from 'vue-router';
import {message} from 'ant-design-vue';
import {CreditCardOutlined} from '@ant-design/icons-vue';
import {Local} from "@/utils/storage.ts";
import {getAddressList, addAddress, setDefaultAddress as setDefaultAddressApi} from "@/api/user";
import AddressForm from '@/components/common/AddressForm.vue';
import {getCouponList, getSurcharge, createOrder} from "@/api/order";
import DateFormatter from '@/components/common/DateFormatter.vue';
import {useCurrencyStore} from '@/store';

const {proxy} = getCurrentInstance();
const useCurrency = useCurrencyStore();
const router = useRouter();
const route = useRoute();

const props = defineProps({
  selectedItems: {
    type: Array,
    default: () => []
  },
  currentStep: {
    type: Number,
    default: 0
  }
});

const emit = defineEmits(['update:step', 'update:address', 'update:addressId', 'update:payment', 'update:shipping', 'update:coupon', 'update:finalAmount', 'update:goodsAmount', 'update:orderId']);

// 地址相关状态
const addresses = ref([]);
const selectedAddressId = ref(null);
const showAddressList = ref(false); // 是否显示地址选择列表
const selectedAddress = computed(() => {
  return addresses.value.find(addr => addr.id === selectedAddressId.value) || null;
});
const addressModalVisible = ref(false);
const addressFormRef = ref(null);
const addressLoading = ref(false);
const isPhoneValid = ref(false);

// 支付方式
const paymentMethod = ref('creditcard');

// 配送方式相关状态
const selectedShippingMethod = ref(null);
const selectedShippingData = ref(null);
const standardShippingFee = ref(0); // 标准配送费用
const expressShippingFee = ref(0); // 快速配送费用
const standardShippingFree = ref(true); // 是否免标准配送费
const shippingMethod = ref([])
const insuranceOptions = ref([])
const shippingInsurance = ref(false); // 是否购买运输保险，默认不选中
const shippingInsuranceFee = ref(0); // 运输保险费用
const dutyInsurance = ref(false); // 是否购买关税保险，默认不选中
const dutyInsuranceFee = ref(0); // 关税保险费用
const expandShippingOptions = ref(false); // 控制配送方式列表的展开/折叠

// ==================== 获取运费 ====================
const getShippingFee = async () => {
  try {
    const res = await getSurcharge();
    if (res.code === 200) {
      const freightData = res.data.freight
      shippingMethod.value = [
        {
          id: 2,
          title: freightData.general_freight_title,
          description: freightData.general_freight_description,
          price: calculatePrice(goodsTotal.value, freightData.general_freight)
        },
        {
          id: 1,
          title: freightData.expedited_freight_title,
          description: freightData.expedited_freight_description,
          price: calculatePrice(goodsTotal.value, freightData.expedited_freight)
        }
      ]

      insuranceOptions.value = [
        {
          id: "3",
          title: res.data.freight_insurance.freight_insurance_title,
          description: res.data.freight_insurance.freight_insurance_description,
          price: calculatePrice(goodsTotal.value, res.data.freight_insurance.freight_insurance),
          checked: false,
        },
        {
          id: "4",
          title: res.data.tariff.tariff_title,
          description: res.data.tariff.tariff_description,
          price: calculatePrice(goodsTotal.value, res.data.tariff.tariff),
          checked: false,
        }
      ]

      selectedShippingMethod.value = 2;
      selectedShippingData.value = shippingMethod.value.find(item => item.id === selectedShippingMethod.value);

      if (selectedShippingMethod.value === 2 && goodsTotal.value >= 99) {
        standardShippingFee.value = 0;
      } else {
        standardShippingFee.value = selectedShippingData.value.price;
      }
    } else {
      console.error('Failed to obtain shipping：', response.message);
    }
  } catch (error) {
  }
};
// 计算价格
const calculatePrice = (basePrice, percentage) => {
  return basePrice * parseFloat(percentage)
}
// 格式化价格
const formatPrice = (price) => {
  return (Math.floor(price * 100) / 100).toFixed(2);
};
// 选择运费方式
const handleShippingMethodChange = (e) => {
  selectedShippingMethod.value = e.target.value;
  selectedShippingData.value = shippingMethod.value.find(item => item.id === selectedShippingMethod.value);
  // 标准运输且总价>=99时运费为0
  if (selectedShippingMethod.value === 2 && goodsTotal.value >= 99) {
    standardShippingFee.value = 0;
  } else if (selectedShippingMethod.value === 2) {
    standardShippingFee.value = selectedShippingData.value.price;
  } else if (selectedShippingMethod.value === 1) {
    expressShippingFee.value = selectedShippingData.value.price;
  }
};

// 处理保险选项变更
const handleInsuranceChange = (e) => {
  const changedItem = insuranceOptions.value.find(item => item.id === e.target.id);
  if (changedItem) {
    changedItem.checked = e.target.checked;
    if (changedItem.id === "3") { // 运输保险
      shippingInsurance.value = changedItem.checked;
      shippingInsuranceFee.value = changedItem.checked ? changedItem.price : 0;
    } else if (changedItem.id === "4") { // 关税保险
      dutyInsurance.value = changedItem.checked;
      dutyInsuranceFee.value = changedItem.checked ? changedItem.price : 0;
    }
  }
};

// 商品总额
const goodsTotal = computed(() => {
  if (!props.selectedItems || props.selectedItems.length === 0) {
    return '0.00';
  }

  const total = props.selectedItems.reduce((sum, item) => {
    const price = Number(item.price) || 0;
    const quantity = Number(item.quantity) || 1;
    return sum + (price * quantity);
  }, 0);

  return total.toFixed(2);
});

// 计算总运费
const totalShippingFee = computed(() => {
  let fee = 0;

  // 根据选择的配送方式计算费用
  if (selectedShippingMethod.value === 1) {
    fee += expressShippingFee.value;
  } else if (selectedShippingMethod.value === 2 && goodsTotal.value >= 99) {
    fee = 0; // 标准配送免费
  } else if (selectedShippingMethod.value === 2) {
    fee += standardShippingFee.value;
  }

  return fee;
});

// 计算运输保险费用
const totalShippingInsuranceFee = computed(() => {
  return shippingInsurance.value ? shippingInsuranceFee.value : 0;
});

// 计算关税保险费用
const totalDutyInsuranceFee = computed(() => {
  return dutyInsurance.value ? dutyInsuranceFee.value : 0;
});

// 最终金额
const finalAmount = computed(() => {
  // 先将每个值保留两位小数
  const goods = Math.floor(parseFloat(goodsTotal.value) * 100) / 100;
  const shipping = Math.floor(totalShippingFee.value * 100) / 100;
  const shippingInsurance = Math.floor(totalShippingInsuranceFee.value * 100) / 100;
  const dutyInsurance = Math.floor(totalDutyInsuranceFee.value * 100) / 100;
  const discount = Math.floor(couponDiscount.value * 100) / 100;

  return goods + shipping + shippingInsurance + dutyInsurance - discount;
});

// ==================== 优惠券 ====================
// 优惠券相关状态
const couponCode = ref('');
const verifyingCoupon = ref(false);
const selectedCouponId = ref(null);
const expandCouponList = ref(false); // 控制优惠券列表的展开/折叠
const couponDiscount = ref(0); // 优惠金额

// 选中的优惠券名称
const selectedCouponName = computed(() => {
  if (!selectedCouponId.value) return '';
  const coupon = availableCoupons.value.find(c => c.id === selectedCouponId.value);
  return coupon ? coupon.name : '';
});

// 模拟可用优惠券数据
const availableCoupons = ref([]);

const getCoupon = async () => {
  await getCouponList(1, 1, 100).then(res => {
    if (res.code === 200) {
      availableCoupons.value = res.result.data
    }
  })
}
// 选择优惠券
const handleCouponChange = (e) => {
  // 检查订单金额是否达到99美金
  if (goodsTotal.value < 99) {
    message.warning(`The order amount needs to reach ${useCurrency.currentCurrency.unit + 99} to use the coupon`)
    selectedCouponId.value = null
    return
  }
  selectedCouponId.value = e.target.value;

  const selectedCoupon = availableCoupons.value.find(c => c.id === e.target.value);
  if (selectedCoupon) {
    couponDiscount.value = selectedCoupon.discount_amount;
  }
}

// 监听选中的优惠券变化
watch(selectedCouponId, (newId) => {
  if (newId === null) {
    couponDiscount.value = 0;
  } else {
    const selectedCoupon = availableCoupons.value.find(c => c.id === newId);
    if (selectedCoupon) {
      const goodsTotalValue = parseFloat(goodsTotal.value);
      console.log('---1', selectedCoupon, goodsTotalValue)

      if (goodsTotalValue >= 99) {
        couponDiscount.value = selectedCoupon.discount_amount;
        message.success(`"${selectedCoupon.name}" has been applied to save you ${selectedCoupon.discount_amount}`);
      } else {
        message.warning(`The order amount needs to reach ${useCurrency.currentCurrency.unit + 99} to use the coupon`);
        selectedCouponId.value = null;
        couponDiscount.value = 0;
      }
    }
  }
});

// 表单数据
const formData = ref({
  user_id: Local.get('userInfo')?.id || '',
  last_name: '',
  first_name: '',
  name: '',
  address: '',
  county: 'United States',
  province: '',
  city: '',
  zipcode: '',
  phone: '',
  countryCode: '+1',
  is_default: 0
});

// 默认地址状态
const isDefaultAddress = ref(false);

// 获取地址列表
const fetchAddresses = async () => {
  try {
    const res = await getAddressList({
      page: 1,
      page_size: 10
    });
    if (res.code === 200) {
      addresses.value = res.result.data || [];

      // 如果有默认地址，自动选中
      const defaultAddress = addresses.value.find(addr => addr.is_default === 1);
      if (defaultAddress) {
        selectedAddressId.value = defaultAddress.id;
        showAddressList.value = false; // 如果找到默认地址，隐藏地址列表
      } else if (addresses.value.length > 0) {
        // 如果没有默认地址但有地址，选中第一个
        selectedAddressId.value = addresses.value[0].id;
        showAddressList.value = true; // 显示地址列表让用户选择
      } else {
        // 如果没有地址，显示添加地址提示
        selectedAddressId.value = null;
        showAddressList.value = false;
      }
    }
  } catch (error) {
    console.error('获取地址列表失败:', error);
    message.error('获取地址列表失败，请稍后重试');
  }
};

// 显示添加地址模态框
const showAddAddressModal = () => {
  // 重置表单
  formData.value = {
    user_id: Local.get('userInfo')?.id || '',
    last_name: '',
    first_name: '',
    name: '',
    address: '',
    county: 'United States',
    province: '',
    city: '',
    zipcode: '',
    phone: '',
    countryCode: '+1',
    is_default: 0
  };
  isDefaultAddress.value = false;
  isPhoneValid.value = false;

  addressModalVisible.value = true;
};

// 表单数据更新处理
const onFormDataUpdate = (data) => {
  formData.value = {...data};
};

// 默认地址更新处理
const onDefaultUpdate = (value) => {
  isDefaultAddress.value = value;
  formData.value.is_default = value ? 1 : 0;
};

// 电话验证状态更新
const onPhoneValidUpdate = (valid) => {
  isPhoneValid.value = valid;
};

// 保存地址
const saveAddress = async () => {
  if (!isPhoneValid.value && formData.value.phone) {
    message.error("电话号码格式不正确");
    return;
  }

  // 确保姓名和手机号被正确设置
  formData.value.name = `${formData.value.first_name} ${formData.value.last_name}`.trim();
  formData.value.zip_code = formData.value.zipcode;

  try {
    const valid = await addressFormRef.value.validate();
    if (!valid) {
      return;
    }

    const submitData = {...formData.value};
    const res = await addAddress(submitData);

    if (res.code === 200) {
      message.success("地址添加成功");
      addressModalVisible.value = false;
      fetchAddresses(); // 重新获取地址列表

      // 如果添加的是默认地址，自动选中
      if (submitData.is_default === 1) {
        selectedAddressId.value = res.data?.id;
      }
    } else {
      message.error(res.message || "添加地址失败");
    }
  } catch (error) {
    console.error("添加地址失败:", error);
    message.error("操作失败，请稍后重试");
  }
};

// 显示地址选择列表
const showAddressSelection = () => {
  showAddressList.value = true;
};

// 隐藏地址选择列表
const hideAddressSelection = () => {
  showAddressList.value = false;
};

const prevStep = () => {
  emit('update:step', 0);
};

// 生成订单
const orderParam = ref({
  type: '4',
  address_id: '',
  coupon_id: '',
  goods: [],
  freight_template_id: 2,
  remark: '',
  freight_insurance_id: 0,
  tariff_id: 0,
})
const nextStep = async () => {
  if (!selectedAddressId.value) {
    message.error('请选择收货地址');
    return;
  }

  orderParam.value.address_id = selectedAddressId.value;
  orderParam.value.coupon_id = selectedCouponId.value;
  orderParam.value.goods = props.selectedItems.map(item => {
    return {
      sku_id: item.sku_id,
      num: item.quantity
    }
  });
  orderParam.value.freight_insurance_id = shippingInsurance.value ? 1 : 0;
  orderParam.value.tariff_id = dutyInsurance.value ? 1 : 0;
  orderParam.value.freight_template_id = selectedShippingMethod.value;

  await createOrder(orderParam.value).then(res => {
    if (res.code === 200) {
      emit('update:orderId', res.result.id)
      Local.set('orderId', res.result.id)
    }
  })

  const selectedAddress = addresses.value.find(addr => addr.id === selectedAddressId.value);
  emit('update:address', selectedAddress);
  emit('update:addressId', selectedAddressId.value);
  emit('update:payment', paymentMethod.value);

  // 传递配送方式信息
  const shippingInfo = {
    method: selectedShippingMethod.value,
    fee: Math.floor(totalShippingFee.value * 100) / 100,
    insurance: shippingInsurance.value,
    insuranceFee: Math.floor(totalShippingInsuranceFee.value * 100) / 100,
    dutyInsurance: dutyInsurance.value,
    dutyInsuranceFee: Math.floor(totalDutyInsuranceFee.value * 100) / 100
  };

  console.log('shippingInfo', shippingInfo)

  // 向父组件传递配送信息
  emit('update:shipping', shippingInfo);

  // 传递优惠券信息
  const couponInfo = {
    discount: Number(couponDiscount.value),
    couponId: selectedCouponId.value
  };

  // 向父组件传递优惠券信息
  emit('update:coupon', couponInfo);

  // 传递最终金额
  emit('update:finalAmount', finalAmount.value);

  // 传递商品金额
  emit('update:goodsAmount', Number(goodsTotal.value));

  emit('update:step', 2);
};

// 组件挂载时获取地址列表
onMounted(() => {
  fetchAddresses();
  getShippingFee();
  getCoupon()
});
</script>

<style scoped>
.step-container {
  max-width: 800px;
  margin: 0 auto;
}

.checkout-card {
  margin-bottom: 24px;
}

.section {
  padding: 16px;
}

.section h3 {
  margin-bottom: 16px;
  font-size: 16px;
  color: #333;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

/* 地址相关样式 */
.address-radio {
  display: block;
  margin-bottom: 16px;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid #f0f0f0;
}

.address-info {
  margin-left: 8px;
}

.address-header {
  margin-bottom: 4px;
}

.address-header .name {
  font-weight: bold;
  margin-right: 8px;
}

.address-header .phone {
  color: #666;
  margin-right: 8px;
}

.address-detail {
  color: #999;
}

/* 运费选择相关样式 */
.shipping-options {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 20px;
}

.shipping-option {
  display: block;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid #f0f0f0;
  width: 100%;
}

.shipping-option-content {
  margin-left: 8px;
}

.shipping-name {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.shipping-title {
  font-weight: bold;
  margin-right: 8px;
}

.shipping-price {
  color: #ff4d4f;
  font-weight: bold;
}

.original-price {
  color: #ff4d4f;
  font-weight: bold;
  text-decoration: line-through;
}

.shipping-tag {
  color: #ff4d4f;
  font-weight: bold;
  margin-left: 4px;
}

.shipping-desc {
  color: #999;
  font-size: 13px;
}

.shipping-add-ons {
  margin-top: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.shipping-add-on {
  display: block;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid #f0f0f0;
  width: 100%;
}

.add-on-content {
  margin-left: 8px;
}

.add-on-name {
  display: flex;
  justify-content: space-between;
  font-weight: bold;
  margin-bottom: 4px;
}

.add-on-price {
  color: #ff4d4f;
}

.add-on-desc {
  color: #999;
  font-size: 13px;
}

/* 支付方式相关样式 */
.payment-radio {
  display: flex;
  align-items: center;
  margin-right: 30px;
}

.payment-icon {
  font-size: 24px;
  color: #fd7e14;
}

.payment-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 优惠券相关样式 */
.coupon-container {
  margin-bottom: 16px;
}

.coupon-input {
  margin-bottom: 16px;
}

.available-coupons {
  margin-top: 16px;
}

.coupon-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  width: 100%;
}

.coupon-option {
  display: block;
  width: 100%;
}

.coupon-none {
  padding: 8px 0;
  color: #999;
}

.coupon-card {
  display: flex;
  padding: 16px;
  border-radius: 4px;
  border: 1px solid #f0f0f0;
  transition: all 0.3s;
  background-color: #fff;
}

.coupon-card.selected {
  border-color: #ff4d4f;
  background-color: #fff1f0;
}

.coupon-amount {
  font-size: 24px;
  font-weight: bold;
  color: #ff4d4f;
  margin-right: 16px;
  display: flex;
  align-items: center;
  min-width: 80px;
}

.coupon-info {
  flex: 1;
}

.coupon-name {
  font-weight: bold;
  margin-bottom: 4px;
}

.coupon-desc {
  color: #666;
  font-size: 13px;
  margin-bottom: 4px;
}

.coupon-valid {
  color: #999;
  font-size: 12px;
}

/* 最终金额确认相关样式 */
.final-amount-section {
  background-color: #fff9f9;
  border-radius: 8px;
  border: 1px solid #ffebeb;
  padding: 20px;
  margin-top: 10px;
}

.final-amount-section h3 {
  color: #ff4d4f;
  font-weight: bold;
  margin-bottom: 20px;
}

.final-amount-container {
  display: flex;
  flex-direction: column;
}

.final-amount-details {
  width: 100%;
  margin-bottom: 20px;
}

.final-amount-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  color: #666;
}

.final-amount-row.discount {
  color: #52c41a;
}

.final-amount-total {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 20px;
  font-weight: bold;
  padding-top: 20px;
  border-top: 1px dashed #ffbfbf;
}

.amount-value {
  color: #ff4d4f;
  font-size: 28px;
}

.step-footer {
  display: flex;
  justify-content: space-between;
  padding: 16px 0;
}

@media (max-width: 768px) {
  .step-container {
    padding: 0 16px;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .address-radio,
  .shipping-option,
  .shipping-add-on,
  .coupon-card {
    padding: 8px;
  }

  .address-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .coupon-amount {
    font-size: 20px;
    min-width: 60px;
  }

  .final-amount-total {
    font-size: 18px;
  }

  .amount-value {
    font-size: 24px;
  }

  .step-footer {
    flex-direction: column;
    gap: 12px;
  }
}

/* 已选地址相关样式 */
.selected-address {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-radius: 4px;
  background-color: #f9f9f9;
  margin-bottom: 16px;
}

.selected-address-info {
  flex: 1;
}

.no-address {
  text-align: center;
  padding: 20px 0;
}

.add-address-btn {
  margin-top: 16px;
}

.address-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.address-list-footer {
  margin-top: 16px;
  text-align: right;
}

/* 已选优惠券相关样式 */
.selected-coupon {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-radius: 4px;
  background-color: #fff1f0;
  border: 1px dashed #ffccc7;
  margin-top: 16px;
}

.selected-coupon-info {
  flex: 1;
}

.coupon-value {
  font-weight: bold;
  margin: 0 8px;
}

.coupon-discount {
  color: #ff4d4f;
  font-weight: bold;
}

.available-coupons-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-top: 16px;
  border-top: 1px dashed #f0f0f0;
}

.coupon-list-footer {
  margin-top: 16px;
  text-align: right;
}

/* 已选配送方式相关样式 */
.selected-shipping {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-radius: 4px;
  background-color: #f9f9f9;
  margin-bottom: 16px;
}

.selected-shipping-info {
  flex: 1;
}

.shipping-action {
  margin-left: 16px;
}

.selected-add-ons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}

.add-on-tag {
  display: inline-flex;
  align-items: center;
  padding: 2px 8px;
  border-radius: 4px;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  color: #1890ff;
  font-size: 12px;
}

.shipping-options-footer {
  margin-top: 16px;
  text-align: right;
}

:deep(.ant-checkbox-checked:after) {
  border: none;
}
</style>
